//
//  FindViewController.m
//  自定义导航栏
//
//  Created by Jason on 2022/6/16.
//

#import "FindViewController.h"
#import "HMSegmentedControl.h"
#import "HomeFeedViewController.h"
#import "CategoryTypeModel.h"

@interface FindViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) HMSegmentedControl *segmentControl;

@property (nonatomic, strong) UIScrollView *scrollView;


@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *arr;

@end

@implementation FindViewController

-(NSArray *)arr {
    if (!_arr) {
        _arr = @[
            @{@"name": @"推荐", @"type": @"1", @"bgColor": [UIColor redColor]},
            @{@"name": @"视频", @"type": @"2", @"bgColor": [UIColor yellowColor]},
            @{@"name": @"汽车", @"type": @"4", @"bgColor": [UIColor lightGrayColor]},
            @{@"name": @"健身", @"type": @"5", @"bgColor": [UIColor purpleColor]},
            @{@"name": @"美食", @"type": @"6", @"bgColor": [UIColor orangeColor]},
            @{@"name": @"游戏", @"type": @"7", @"bgColor": [UIColor greenColor]},
            @{@"name": @"学习", @"type": @"8", @"bgColor": [UIColor greenColor]},
            @{@"name": @"科技数码", @"type": @"9", @"bgColor": [UIColor greenColor]}
        ];
    }
    return _arr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    
    [self loadUI];
    
    //创建全局异步队列
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_group_t group = dispatch_group_create();
//    dispatch_group_enter(group);
//    dispatch_group_async(group, globalQueue, ^{
//        //会先执行网络异步请求
//        [self loadRequest];
//        sleep(6);
//        dispatch_group_leave(group);
//    });
//    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);///一直等待完成
//    dispatch_group_notify(group, globalQueue, ^{
//        //回到主线程更新 UI
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self loadUI];
//        });
//        NSLog(@"执行完成");
//    });
    
    //使用GCD的信号量 dispatch_semaphore_t 创建同步请求
//    dispatch_group_t group = dispatch_group_create();
//    // 创建全局并行队列
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_group_async(group, globalQueue, ^{
//        //创建信号量
//        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//        //模拟网络多线程耗时操作
//        dispatch_group_async(group, globalQueue, ^{
//           //
//           // [self loadRequest];
//            sleep(3);
//            NSLog(@"%@---block1结束。。。",[NSThread currentThread]);
//            dispatch_semaphore_signal(semaphore);
//        });
//        NSLog(@"%@---1结束。。。",[NSThread currentThread]);
//        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    });
//
//    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"返回主线程 = %@",[NSThread currentThread]);
//            [self loadUI];
//        });
//        NSLog(@"%@---全部结束。。。",[NSThread currentThread]);
//    });
    
}

#pragma mark - 类别接口
- (void)loadRequest {
    NSLog(@"类别接口");
    [[HttpRequest shareInstance] get:kCategary parameters:@"" success:^(NSURLSessionDataTask * _Nonnull task, HttpResponseModel * _Nonnull responseModel) {
        NSLog(@"类别responseModel = %@",responseModel);
        if (responseModel.code.integerValue == 0) {
            NSLog(@"类别接口请求成功");
            NSArray<CategoryTypeModel *> *arr = [CategoryTypeModel arrayFromJSONArray:responseModel.data];
            self.arr = arr;
            NSLog(@"_arr = %@",self.arr);
        }
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"类别接口请求失败");
        }];
}

#pragma mark - 懒加载segmentControl
-(HMSegmentedControl *)segmentControl {
    if (!_segmentControl) {
        // NSArray *titleArr = @[@"推荐", @"视频", @"母婴",@"直播", @"美食",@"家居家装",@"时尚", @"明星", @"健身", @"职场", @"情感", @"旅行", @"彩妆", @"母婴", @"综艺", @"个护", @"护肤",@"萌娃", @"学习", @"舞蹈", @"发型", @"体育", @"搞笑", @"动漫"];
        
        NSMutableArray *titleArr = [NSMutableArray new];
        for (NSDictionary *dict in self.arr) {
            [titleArr addObject:[dict valueForKey:@"name"]];
        }
//        for (CategoryTypeModel *categoryModel in _arr) {
//            [titleArr addObject:categoryModel.name];
//        }
        
        _segmentControl = [[HMSegmentedControl alloc] initWithSectionTitles: titleArr];
        _segmentControl.segmentEdgeInset = UIEdgeInsetsMake(0, 5, 0, 5);
        if (@available(iOS 13.0, tvOS 13, *)) {
            _segmentControl.backgroundColor = [UIColor secondarySystemGroupedBackgroundColor];
            _segmentControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName :[UIColor labelColor] ,NSFontAttributeName:[UIFont systemFontOfSize:13.0]};
        } else {
            _segmentControl.backgroundColor = kWhiteColor;
            _segmentControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName :kBlackColor ,NSFontAttributeName:[UIFont systemFontOfSize:13.0]};
        }
        
        _segmentControl.titleTextAttributes = @{NSForegroundColorAttributeName :kLightGrayColor ,NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
       
        //设置横线的宽度（样式）
        _segmentControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        //设置横线的位置，在文字下面
        _segmentControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        //设置横线的高度
        _segmentControl.selectionIndicatorHeight = 0.0f;
        //设置初始默认选中的index
        _segmentControl.selectedSegmentIndex = 0;
       // _segmentControl.tag = 24;
        
        __weak typeof(self) weakSelf = self;
        //点击每个segment时候触发的事件
        _segmentControl.indexChangeBlock = ^(NSInteger index) {
            [weakSelf.scrollView scrollRectToVisible:CGRectMake(kSPScreenWidth * index, 0, kSPScreenWidth, weakSelf.scrollView.bounds.size.height) animated:YES];
            
            HomeFeedViewController *hfVC = (HomeFeedViewController *)[weakSelf.childViewControllers objectAtIndex:index];
            if (!hfVC.isCurrentLoad) {
                hfVC.isCurrentLoad = YES;
            }
            
        };
    }
    return _segmentControl;
}


#pragma mark - 懒加载scrollView
-(UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.bounces = NO;
        _scrollView.backgroundColor = kClearColor;
        _scrollView.pagingEnabled = YES;
        _scrollView.alwaysBounceHorizontal = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
//        if (@available(iOS 11.0, *)) {
//            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        } else {
//        }
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
        NSInteger selectIndex = self.segmentControl.selectedSegmentIndex;
        [self.scrollView scrollRectToVisible:CGRectMake(selectIndex * kSPScreenWidth, 0, kSPScreenWidth, kSPScreenHeight) animated:NO];
    }
    return _scrollView;
}




#pragma mark - loadUI
- (void)loadUI {
    [self.view addSubview:self.segmentControl];
    [self.segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view);
        make.top.left.right.equalTo(self.view);
        make.height.equalTo(@40);
    }];
    NSLog(@"--frame = %@", NSStringFromCGRect(self.view.frame));
    
   
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segmentControl.mas_bottom);
        make.left.right.equalTo(self.view);
       make.height.equalTo(@(kSPScreenHeight -40 - [UIDevice vg_navigationFullHeight] - [UIDevice vg_tabBarFullHeight]));
        //make.bottom.equalTo(self.tabBarController.tabBar.mas_top);
        
    }];
    NSLog(@"navigationFullHeight = %f, tabBarFullHeight = %f",[UIDevice vg_navigationFullHeight], [UIDevice vg_tabBarFullHeight]);
    
    

    [self.scrollView layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(kSPScreenWidth * self.arr.count, 1);
    NSLog(@"contentSize = %@", NSStringFromCGSize(self.scrollView.contentSize));

    NSLog(@"%f:%f", self.scrollView.frame.size.height, kSPScreenHeight);
    NSLog(@"scrollFrame = %@", NSStringFromCGRect(self.scrollView.frame));
    NSLog(@"---contentSize = %@", NSStringFromCGSize(self.scrollView.contentSize));
    

    for (int i = 0; i < self.arr.count; i++) {
        NSDictionary *dict = [self.arr objectAtIndex:i];
        //获取模型数据
       // CategoryTypeModel *model = [self.arr objectAtIndex:i];
        HomeFeedViewController *hfVC = [HomeFeedViewController new];
        
        hfVC.type = [dict valueForKey:@"type"];
        hfVC.bgColor = [dict valueForKey:@"bgColor"];
       // hfVC.type = [NSString stringWithFormat:@"%ld",model.categoryTypeId];
        
        hfVC.isCurrentLoad = i == 0;
        NSLog(@"hfVC.type = %@",hfVC.type);
        [[hfVC view] setFrame:CGRectMake(i * kSPScreenWidth, 0, kSPScreenWidth, self.scrollView.frame.size.height)];
        NSLog(@"self.scrollView.frame.size.height: %f", self.scrollView.frame.size.height);
        NSLog(@"self.view.frame.size.height: %f", hfVC.view.frame.size.height);
        [self addChildViewController:hfVC];
        [self.scrollView addSubview:[hfVC view]];
    }
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = scrollView.contentOffset.x / pageWidth;
    [self.segmentControl setSelectedSegmentIndex:page animated:YES];
    NSLog(@"pageWidth = %f - page = %ld",pageWidth, page);
    HomeFeedViewController *hfVC = (HomeFeedViewController *)self.childViewControllers[page];
    if (!hfVC.isCurrentLoad) {
        hfVC.isCurrentLoad = YES;
    }
    
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
